package com.mike.server.util;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

import com.mike.game.protocols.SystemProtocols;
import com.mike.server.engine.IGameMessage;
import com.mike.server.engine.ServiceDispatherThread;

public class GameMessageCreater implements Runnable {
	
	private static ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(1);
	private static GameMessageCreater instance = new GameMessageCreater(new IGameMessage() {
		@Override
		public int getType() {
			return ROLE_SYSTEM;
		}
		
		@Override
		public int getId() {
			int nextInt = r.nextInt(RANDOM_RATE);
			if(nextInt < RANDOM_RATE / 3) {
				return SystemProtocols.UPDATE_ROLE;
			} else if (nextInt < RANDOM_RATE / 2){
				return SystemProtocols.DELETE_ROLE;
			} else {
				return SystemProtocols.CREATE_ROLE;
			}
		}
	});
	
	private static volatile boolean isRuning = false;
	private static final Logger LOG = Logger.getLogger(GameMessageCreater.class);
	private IGameMessage gameMessage;
	private static final int RANDOM_RATE = 2000;
	private static Random r = new Random();
	
	public GameMessageCreater(IGameMessage gameMessage) {
		if(null != gameMessage) {
			this.gameMessage = gameMessage;
		}
	}
	
	public static GameMessageCreater getInstance() {
		return instance;
	}
	
	@Override
	public void run() {
		while (true) {
			if(!isRuning) {
				continue;
			}
			ServiceDispatherThread.getInstance().addMessage(this.gameMessage);
			try {
				TimeUnit.MILLISECONDS.sleep(r.nextInt(RANDOM_RATE));
			} catch (InterruptedException e) {
				LOG.error("线程中断，恢复中断标记");
				Thread.currentThread().interrupt();
			}
		}
	}
	
	public void stop() {
		isRuning = false;
	}
	
	public void start() {
		isRuning = true;
		newFixedThreadPool.execute(this);
	}

}
